<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="20">
				<div class="layout-padding-auto layout-padding-view">
					<el-input prefix-icon="search" v-model="filterText" placeholder="请输入关键字搜索" class="mb-2" />
					<el-scrollbar>
						<el-tree
							ref="treeRef"
							:data="treeData.list"
							:props="treeData.defaultProps"
							@node-click="handleNodeClick"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							:filter-node-method="filterNode"
						/>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<el-row>
						<el-form :model="form" ref="dataFormRef" :inline="true" @keyup.enter="getDataList" :rules="dataRules" v-loading="loading">
							<el-form-item prop="dateTime" label="时间" class="w-[280px]">
								<el-date-picker
									size="small"
									v-model="form.dateTime"
									type="daterange"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							<el-form-item prop="deviceId" label="设备">
								<el-select placeholder="请选择设备" v-model="form.deviceId" size="small" filterable>
									<el-option v-for="item in deviceList" :key="item.id" :value="item.id" :label="item.name" />
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button icon="search" type="primary" class="ml-2" size="small" @click="getDataList">查询</el-button>
							</el-form-item>
						</el-form>
					</el-row>
					<div class="h-[calc(100%-60px)] overflow-y-auto">
						<el-card>
							<div class="flex justify-end">
								<el-radio-group v-model="chartType" size="small">
									<el-radio-button label="饼图" />
									<el-radio-button label="柱状图" />
								</el-radio-group>
							</div>
							<div class="w-full h-[320px]">
								<PieChart :data="chartData" name="污染等级" v-if="chartType === '饼图'" radius="70%" />
								<BarChart ref="barChartRef" :loading="loading" :data="barChartData.data" v-if="chartType === '柱状图'" />
							</div>
						</el-card>
						<el-card class="mt-4">
							<el-table :data="chartData">
								<el-table-column label="天数" align="center" prop="value" sortable />
								<el-table-column label="污染等级" align="center" prop="name">
									<template #default="{ row }">
										<div class="flex items-center justify-center">
											<div :style="{ backgroundColor: row.itemStyle.color }" class="w-[30px] h-[20px] rounded-sm"></div>
											<div class="ml-1 w-[80px] text-[#000] font-semibold">{{ row.name }}</div>
										</div>
									</template>
								</el-table-column>
							</el-table>
						</el-card>
					</div>
				</div>
			</pane>
		</splitpanes>
	</div>
</template>

<script setup lang="ts" name="pollutionAnalysis">
import { fetchList } from '/@/api/platform/pollutionAnalysis';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { fetchListByTag } from '/@/api/platform/airMonitorEquipment';
import { handleTree } from '/@/utils/other';
import { level, optionType, ItemType, TreeType, ChartsDataType } from './data';
import { formatDate } from '/@/utils/formatTime';
import { useMessage } from '/@/hooks/message';
const PieChart = defineAsyncComponent(() => import('/@/components/Echarts/pie.vue'));
const BarChart = defineAsyncComponent(() => import('./components/barChart.vue'));
// 定义变量内容
const treeRef = ref();
const filterText = ref('');
const dataFormRef = ref();
const loading = ref(true);
const chartType = ref('饼图');
const siteId = ref();
const chartData = ref<ChartsDataType[]>([]);
const deviceList = ref<optionType[]>([]);
const barChartData = reactive<{ data: ChartsDataType[] }>({
	data: [],
});
const barChartRef = ref();

// 区域树使用的数据
const treeData = reactive({
	list: [] as TreeType[],
	defaultProps: {
		label: 'name',
	},
});
// 搜索树监听
watch(filterText, (val) => {
	treeRef.value!.filter(val);
});
const form = reactive({
	deviceId: '',
	dateTime: [formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'YYYY-mm-dd'), formatDate(new Date(), 'YYYY-mm-dd')],
});

// 定义校验规则
const dataRules = ref({
	deviceId: [{ required: true, message: '请选择', trigger: 'change' }],
	dateTime: [{ required: true, message: '请选择', trigger: 'change' }],
});
// 点击树
const handleNodeClick = (e: any) => {
	siteId.value = e.id;
	getDeviceList();
};
const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			treeData.list = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			siteId.value = treeData.list[0]?.id;
			getDeviceList();
			nextTick(() => {
				unref(treeRef)?.setCurrentKey(siteId.value, true);
			});
		}
	});
};
const filterNode = (value: string, data: TreeType) => {
	if (!value) return true;
	return data.name.includes(value);
};
const getDataList = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	try {
		loading.value = true;
		const res = await fetchList({ dt0: form.dateTime[0], dt1: form.dateTime[1], tp: 'DailyAvg', monitorEquipmentId: form.deviceId });
		formatPollutionData(res.data);
		formatBarChartData(res.data);
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
const formatPollutionData = (data: ItemType[]) => {
	const list: ChartsDataType[] = [];
	for (let i = 0; i < level.length; i++) {
		const d = level[i];
		const len = data.filter((f) => f.pollutionDegree === d.pollutionDegree).length;
		list.push({
			value: len,
			name: d.label,
			itemStyle: {
				color: d.color,
			},
		});
	}
	chartData.value = list;
};
const formatBarChartData = (data: ItemType[]) => {
	const list: ChartsDataType[] = [];
	for (let i = 0; i < level.length; i++) {
		const d = level[i];
		const len = data.filter((f) => f.pollutionDegree === d.pollutionDegree).length;
		list.push({
			value: len,
			itemStyle: {
				color: d.color,
			},
		});
	}
	barChartData.data = list;
};
// 树节点查找设备
const getDeviceList = () => {
	fetchListByTag({ tag: unref(siteId) }).then((res) => {
		deviceList.value = res.data;
		if (res.data.length) {
			form.deviceId = res.data[0].id;
			getDataList();
		} else {
			form.deviceId = '';
		}
	});
};
onMounted(() => {
	getTreeDate();
	formatPollutionData([]);
	formatBarChartData([]);
	setTimeout(() => {
		loading.value = false;
	}, 2000);
});
</script>
